import { IMenubarIIList } from '../type/store/auth';
import { authMenuTree } from './routerAdapter';
import { store } from '/@/store/index';
import { IObject } from '../global';
// 引入动态路由页面
const modules = import.meta.glob('../views/**/**.vue');
const components: IObject<() => Promise<typeof import('*.vue')>> = {
    Layout: () => import('/@/layout'),
    LayoutBlank: () => import('/@/layout/blank.vue'),
    404: () => import('/@/layout/error-page/404.vue')
};
const pages: IObject<() => Promise<typeof import('*.vue')>> = {};

const componentsIngore: Array<string> = []; // 忽略的页面
Object.keys(modules).forEach((key) => {
    if (/components/.test(key)) {
        return;
    }
    const nameMatch = key.match(/^\.\.\/views\/(.*)\/(.*)\.vue/);
    if (!nameMatch) return;
    let [, namePath, name] = nameMatch;
    // 如果页面以index命名，则使用父文件夹作为name
    if (nameMatch[2].toLowerCase() === 'index') {
        const nameSplit = nameMatch[1].split('/');
        name = nameSplit[nameSplit.length - 1];
    } else {
        namePath = [namePath, name].join('/');
    }
    if (componentsIngore.includes(name)) {
        return;
    }
    components[name] = modules[key] as () => Promise<typeof import('*.vue')>;
    pages[`/${namePath}`] = modules[key] as () => Promise<typeof import('*.vue')>;
    console.log(`[pages] /${namePath}`);
});

const asyncRouter: Array<IMenubarIIList> = [
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: components['404'],
        meta: {
            title: 'NotFound',
            icon: '',
            hidden: true
        },
        redirect: {
            name: '404'
        }
    }
];

const routerList: Array<IMenubarIIList> = [
    {
        name: 'Layout',
        path: '/',
        component: components['Layout'],
        meta: { title: '', icon: '' },
        children: []
    },
    {
        name: 'FullScreen',
        path: '/',
        component: components['LayoutBlank'],
        meta: { title: '', icon: '' },
        children: []
    }
];
export const generatorDynamicRouter = (data: Array<IMenubarIIList>): void => {
    const menuList: Array<IMenubarIIList> = authMenuTree(
        data,
    import.meta.env.VITE_MENU_SIGN as string
    );
    const f = (data: Array<IMenubarIIList>, pData: IMenubarIIList | null) => {
        for (let i = 0, len = data.length; i < len; i++) {
            const v: IMenubarIIList = data[i];
            if (typeof v.component === 'string' || !v.component) {
                v.component = (v.path && pages[v.path]) || components[v.component] || components['404'];
            }
            if (!v.meta.permission || (pData && v.meta.permission.length === 0)) {
                v.meta.permission =
          pData && pData.meta && pData.meta.permission
              ? pData.meta.permission
              : [];
            }
            if (v.meta.fullScreen) {
                v.hasFullScreen = true;
                pData && (pData.hasFullScreen = true);
            }
            if (v.children && v.children.length > 0) {
                f(v.children, v);
                if (v.hasFullScreen && pData) {
                    pData.hasFullScreen = true;
                }
            }
        }
    };
    f(menuList, null);
    menuList.forEach((data) => {
        routerList[0].children?.push(data);
        data.hasFullScreen && routerList[1].children?.push(data);
    });
    asyncRouter.forEach((v) => routerList.push(v));
    console.log('routerList', routerList);
    console.log('menuList', menuList);
    store.commit('layout/setRoutes', routerList);
    store.commit('layout/setMenus', menuList);
};
